import Mn from 'backbone.marionette';
import Radio from "backbone.radio";

/** Instantiate the propper viewer view for a NodeFileModel
 *
 * Requires PreviewService to be setup.
 */
const NodeFileViewerFactoryClass = Mn.Object.extend({
    /**
     *
     * @param {NodeFileModel} file the file object to be viewed
     * @param {Object} kwargs extra args to be passed as-is to viewer constructor
     * @returns {Mn.View} (or null if no viewer is found)
     */
    getViewer(file, kwargs) {
        const mime = file.get('mimetype');
        const id = file.get('id');
        const klass = Radio.channel('config').request('get:viewer:class', file);

        if (klass) {
            const args = Object.assign(
                {
                    fileUrl: `/files/${id}?action=download`,
                    fileLabel: file.get('label'),
                },
                kwargs,
            );
            return new klass(args);
        } else {
            console.warn(
                `Trying to render unknown file type: "${mime} for file #${id}`
            );
            return null;
        }
    },
});

let NodeFileViewerFactory = new NodeFileViewerFactoryClass();

export default NodeFileViewerFactory;
